﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Crimson;
using Crimson.Module;
using Ornament.Util;

public partial class Admin_Crimson_Controls_InfoTypeTree : UserControl
{
    /// <summary>
    /// 点击树节点触发的 客户端函数名称
    /// </summary>
    public string ClientMethod
    {
        set { ViewState["ClientScript"] = value; }
        get{return ViewState["ClientScript"]==null?null:(string)ViewState["ClientScript"];}
    }

    public event EventHandler<DataEvent<InfoType>> OnSelectedNodeChanged;
    /// <summary>
    /// 重新绑定树的数据。
    /// </summary>
    public void DataBindTree()
    {
        treeview1.Nodes.Clear();
        IList<InfoType> result = InfoManager.DaoFactory.InfoTypeDao.GetFirstLevel();
        var rootNode = new TreeNode
                           {
                               Text = "根节点",
                               Value = Guid.Empty.ToString(),

                           };
        treeview1.Nodes.Clear();
        treeview1.Nodes.Add(rootNode);
        fillTreeList(rootNode.ChildNodes, result);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataBindTree();
        }
    }

    private void fillTreeList(TreeNodeCollection collection, IEnumerable<InfoType> typeList)
    {
        foreach (InfoType type in typeList)
        {
            var newNode = new TreeNode
                           {
                               Text = type.Name,
                               Value = type.Id.ToString(),
                           };
            if (ClientMethod != null)
            {
                newNode.NavigateUrl = String.Format("javascript:" + ClientMethod + "('{0}','{1}','{2}')", type.Id.ToString(), type.Name,type.OrderId);
            }
            collection.Add(newNode);
            if (type.Count != 0)
            {
                fillTreeList(newNode.ChildNodes, type.GetChilds());
            }
        }
    }

    protected void selectNode(object sender, EventArgs e)
    {
        if (OnSelectedNodeChanged != null && treeview1.SelectedNode.Value != Guid.Empty.ToString())
        {
            InfoType data = InfoManager.DaoFactory.InfoTypeDao.Get(new Guid(treeview1.SelectedNode.Value));
            OnSelectedNodeChanged(this, new DataEvent<InfoType>(data));
        }
    }
    
}